<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">

        <title>Utbudstjänst - Tjänster</title>

        <meta name="description" content="">
        <meta name="author" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">

        <link rel="stylesheet" href="../css/font-awesome.css">
        <link rel="stylesheet" href="../css/bootstrap.css">
        <link rel="stylesheet" href="../css/prism.css">
        <link rel="stylesheet" href="../css/style.css">
        <link rel="stylesheet" href="../css/chosen.min.css">
        <link rel="stylesheet" href="../css/bootstrap-responsive.css">
        <link rel="stylesheet" href="../css/datepicker.css">
        <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.21.custom.css">
        <link rel="stylesheet" href="../css/application-ocean-breeze.css">
        <link rel="stylesheet" href="../css/msgGrowl.css" type="text/css" charset="utf-8" />
        <link rel="stylesheet" href="../css/jquery.msgbox.css">
        <link rel="stylesheet" href="../css/jquery.dataTables.css">
        <script src="../js/lib/modernizr-2.5.3.min.js"></script>
    </head>

    <body>

        <style>
            .xtext-left { text-align: left !important; }
            .xtext-right { text-align: right !important; }
            .xtext-center { text-align: center !important; }
            #addCodesBody td {
                padding: 3px 10px;
                border-top: none;
            }
        </style>

        <script id="codeSystemTemplate" type="text/html">


            <div class="control-group" id="codeSystemName">
                <strong class="span3" id="codeSystemName"></strong>
                <select id="code" class="chosen-nosearch"></select>
                <button id="bAddCode" class="btn listen-click" disabled="true"><i class="icon-plus"></i> L&auml;gg till</button>
            </div>
        </script>

        <script id="detailTemplate" type="text/html">
            <form id="edit-product">
                <h2 class="closeable unmodified"><i class="icon-check-minus modified"></i><span id="edit-title">Ny tjänst</span></h2>
                <div class="row-fluid unmodified">
                    <div class="alert">
                        <strong>Du har osparade ändringar!</strong> För att stänga raden måste du <a class="action-save">spara</a> eller <a class="action-cancel">avbryta</a>.
                    </div>
                </div>

                <div class="row-fluid">
                    <div class="span8">
                        <input id="productId" type="hidden" />
                        <div class="control-group">
                            <label>Namn</label>
                            <div class="controls">
                                <input id="productDisplayName" class="input-xxlarge" type="text" required>
                            </div>
                        </div>
                        <div class="control-group">
                            <label>Beskrivning</label>
                            <div class="controls">
                                <textarea id="productDescription" class="input-xxlarge" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="span4">
                        <fieldset>
                            <div class="control-group">
                                <label for="status" class="control-label">Status</label>
                                <div class="controls">
                                    <select id="productStatus" class="chosen-nosearch listen-change">
                                        <option value="ACTIVE">Aktiv</option>
                                        <option value="INACTIVE">Inaktiv</option>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="produkttyp" class="control-label">Väntetidstyp</label>
                                <div class="controls" id="vantetider">
                                    <input type="checkbox" id="Mottagning" name="Mottagning" value="Mottagning" class="listen-change checkbox"> Mottagning</input><br>
                                    <input type="checkbox" id="Operation" name="Operation" value="Operation" class="listen-change checkbox"> Operation</input><br>
                                    <input type="checkbox" id="OperationMottagning" name="Operation/mottagning" value="Operation/mottagning" class="listen-change checkbox"> Operation/mottagning</input><br>
                                </div>
                            </div>
                        </fieldset>
                    </div> <!-- span4 -->
                </div>
                <div class="row-fluid">
                    <div class="span12 padded">
                        <fieldset>
                            <legend>Kodning</legend>

                            <div class="control-group">
                                <table id="productCodeTable" class="table">
                                    <thead>
                                        <tr>
                                            <th width="30%">Kodramverk</th>
                                            <th width="5%">Kod</th>
                                            <th width="55%">Beskrivning</th>
                                            <th width="5%"></th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                            <div id="codesAlert" class="alert" style="display:none;">
                                <strong>OBS!</strong> Verksamhetskod saknas.
                            </div>
                            <div class="control-group">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th width="25%">Kodramverk</th>
                                            <th width="50%">Kod</th>
                                            <th width="25%"></th>
                                        </tr>
                                    </thead>
                                </table>
                                <div id="addCodesBody" class="padded">
                                </div>
                            </div>
                        </fieldset>
                    </div> <!-- span12 -->

                </div> <!-- row-fluid -->
                <!-- Actions Save & Cancel -->
                <div class="row-fluid actions-item">
                    <div class="span12 unmodified">
                        <div class="pull-right">
                            <a class="btn action-cancel"><i class="icon-remove"></i> Avbryt</a>
                            <a class="btn btn-primary action-save" disabled="disabled"><i class="icon-thumbs-up"></i> Spara</a>
                        </div>
                    </div>
                </div>
            </form>
        </script>

        <div id="wrapper">
            <div id="headerPlaceholder"></div>
            <!-- Main content -->
            <div id="content">
                <div class="container">
                    <div id="createPlaceholder" class="info_row hidden"></div>   

                    <div class="row">
                        <div class="span12">
                            <!-- Product list -->
                            <table id ="productsTable" class="table table-hover table-striped">
                                <thead>
                                    <tr>                       
                                        <th width="10%" class="sortable">Produkt-ID</th>
                                        <th width="35%" class="sortable">Namn</th>
                                        <th width="35%" class="sortable">Beskrivning</th>
                                        <th width="15%" class="sortable">Status</th>
                                        <th width="15%" class="sortable">Senast uppdaterad</th>
                                    </tr>
                                </thead>
                                <tbody id ="productsBody">
                                </tbody>
                            </table>
                        </div><!--End Content-->
                    </div> <!-- /.row -->
                </div> <!-- /.container -->
            </div> <!-- /#content -->
        </div> <!-- /#wrapper -->

        <script src="../js/lib/jquery-1.7.2.min.js"></script>
        <script src="../js/lib/jquery-ui-1.8.21.custom.min.js"></script>
        <script src="../js/lib/jquery.ui.touch-punch.min.js"></script>
        <script src="../js/lib/bootstrap.min.js"></script>
        <script src="../js/lib/moment.min.js"></script>
        <script src="../js/lib/jquery.tablesorter.min.js"></script>
        <script src="../js/lib/jquery.dataTables.js"></script>
        <script src="../js/lib/jquery.validate.js"></script>
        <script src="../js/lib/chosen.jquery.min.js"></script>
        <script src="../js/lib/msgGrowl.min.js"></script>
        <script src="../js/lib/jquery.cookie.js"></script>
        <script src="../js/lib/jquery-handlebars-1.1.4.min.js"></script>
        <script src="../js/md.js"></script>
        <script src="../js/common.js"></script>
        <script>
            var productView = config.guiURL + '/view/product';
            var productGet = config.productURL + '/products';
            var productPut = config.productURL + '/products';
            var productPost = config.productURL;

            commonInit({
                tabProduct: true,
                viewDataUrl: productView,
                mastheadTitle: 'Tjänster',
                mastheadSubtitle: 'Administrera och lägg till tjänster och produkter.',
                mastheadContent: '<a id="bAddProduct" class="pull-right btn" onclick="$(\'#productsTable\').MasterDetail(\'toggleCreateDetail\');"><i class="icon-plus"></i> Lägg till tjänst</a>'
            });

            $("#productsTable").MasterDetail({
                masterData: viewData.product,
                masterTableId: 'productsTable',
                masterColumns: [
                    {
                        mData: 'name',
                        mRender: MasterDetail.renderString
                    }, {
                        mData: 'displayName',
                        mRender: MasterDetail.renderString
                    }, {
                        mData: 'description',
                        mRender: MasterDetail.renderString
                    }, {
                        mData: 'status',
                        mRender: MasterDetail.renderActiveNoActive
                    }, {
                        mData: 'updateTime',
                        mRender: MasterDetail.renderDate
                    }
                ],
                initDetail: initDetail,
                createDetail: createDetail,
                updateDetail: updateDetail,
                validateDetail: validateDetail
            });

            /**
             * Callback method for init master detail
             * 
             * @param {type} container
             * @param {type} data
             * @returns {undefined}
             */
            function initDetail(container, data) {
                if (data) {
                    $('#edit-title', container).text(data.displayName);
                    $('#productId', container).val(data.name);
                    $('#productDisplayName', container).val(data.displayName);
                    $('#productDescription', container).val(data.description);
                    $('#productStatus', container).val(data.status);
                }
                if (data) {
                    productCodes = getProductCodes(data.name);
                    var codeTable = $('#productCodeTable', container).dataTable({
                        aoColumns: [
                            {mData: 'codeSystem',
                                mRender: MasterDetail.renderString
                            },
                            {mData: 'code',
                                mRender: MasterDetail.renderString
                            },
                            {mData: 'displayName',
                                mRender: MasterDetail.renderString
                            },
                            {sDefaultContent: '<a class="delete-code listen-click"><i class="icon-trash"></i></a>',
                                bSortable: false,
                                bSearchable: false
                            }
                        ],
                        bDeferRender: true,
                        bFilter: false,
                        bDestroy: true,
                        bSortCellsTop: true,
                        bPaginate: false,
                        bInfo: false,
                        aaData: productCodes,
                        fnCreatedRow: function(row, data, dataIndex) {
                            $('.delete-code', row).click(function() {
                                codeTable.fnDeleteRow(row);
                            });
                        }
                    });

                    if (productCodes !== null) {
                        setWaitingTimeCheckbox(productCodes, container);
                    }

                } else {
                    var codeTable = $('#productCodeTable', container).dataTable({
                        aoColumns: [
                            {mData: 'codeSystem',
                                mRender: MasterDetail.renderString
                            },
                            {mData: 'code',
                                mRender: MasterDetail.renderString
                            },
                            {mData: 'displayName',
                                mRender: MasterDetail.renderString
                            },
                            {sDefaultContent: '<a class="delete-code listen-click"><i class="icon-trash"></i></a>',
                                bSortable: false,
                                bSearchable: false
                            }
                        ],
                        bDeferRender: true,
                        bFilter: false,
                        bDestroy: true,
                        bSortCellsTop: true,
                        bPaginate: false,
                        bInfo: false,
                        aaData: [],
                        fnCreatedRow: function(row, data, dataIndex) {
                            $('.delete-code', row).click(function() {
                                codeTable.fnDeleteRow(row);
                            });
                        }
                    });

                }
                $.each(viewData.codeSystem, function(i, c) {
                    // @FIXME A hack, UI should not show these two codesystems at the moment
                    if (c.oid === 'oid.sll.vantetider' || c.oid === 'oid.service.catalogue.medspec.type') {
                        return;
                    }
                    var codeSystem = $($('#codeSystemTemplate').html());
                    $('#codeSystemName', codeSystem).html(c.name);

                    var codeSelect = $('#code', codeSystem);
                    codeSelect.append('<option></option>');
                    $.each(viewData.codeSystem[c.oid].codes, function(key, val) {
                        if (val.displayName) {
                            codeSelect.append('<option value="' + val.code + '">' + val.code + ' - ' + val.displayName + '</option>');
                        }
                    });
                    codeSelect.chosen({
                        placeholder_text_single: 'Välj kod...',
                        disable_search_treshold: 10,
                        width: '380px'
                    });
                    codeSelect.on('change', function(evt, params) {
                        $('#bAddCode', codeSystem).prop('disabled', false);
                    });
                    $('#bAddCode', codeSystem).click(function() {
                        addCodeToTableView(codeTable, codeSelect, c.oid);
                        $('#bAddCode', codeSystem).prop('disabled', true);
                    });
                    $('#addCodesBody', container).append(codeSystem);
                });
            }

            /**
             * Callback method for master detail create 
             * 
             * @param {type} container
             * @param {type} data
             * @returns {createDetail.retData|productData}
             */
            function createDetail(container, data) {
                /* $('#edit-product', container).validate({
                 rules: {
                 productDisplayName: "required",
                 productDescription: "required"
                 },
                 messages: {
                 productDisplayName: "Namn måste anges",
                 productDescription: "Beskrivning måste anges"
                 }
                 });*/
                var retData = createProduct(container);
                if (retData !== null) {
                    retData.codes = setCodes(retData.name, container);
                }
                return retData;

            }

            /**
             * Callback method for master detail update
             * 
             * @param {type} container
             * @returns {productData|undefined|updateDetail.retData}
             */
            function updateDetail(container) {
                var retData = updateProduct(container);

                if (retData !== null) {
                    retData.codes = setCodes(retData.name, container);
                }
                return retData;
            }

            /**
             * Validates form
             * 
             * @param {type} container
             * @returns {true or false}
             */
            function validateDetail(container) {
                var $validator = $('#edit-product').validate({
                    rules: {
                        productDisplayName: {
                            required: true,
                            minlength: 2
                        }
                    },
                    messages: {
                        productDisplayName: "Namn måste anges",
                    }
                });


                var isValid = $('#productDisplayName').valid();
                return isValid;
            }

            /**
             * 
             * @param {type} container
             * @returns {productData}
             */
            function createProduct(container) {
                var retData = null;
                var data = {
                    description: $('#productDescription', container).val(),
                    status: $('#productStatus', container).val(),
                    updatedByHsaid: $('#productStatus', container).val(),
                    displayName: $('#productDisplayName', container).val()
                };
                $.ajax({
                    url: productPost + '/products',
                    type: 'POST',
                    data: JSON.stringify(data),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(productData) {
                        showGrowlMessage('Produkt skapad.');
                        retData = productData;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                        retData = false;
                        if (textStatus==='error' && errorThrown==='Unauthorized') {
                            alert("Din användarsession har gått ut, du måste logga in på nytt!")
                            $(location).attr('href','../');
                        }
                    }
                });
                return retData;
            }

            /**
             * Calls REST-API to update product
             * 
             * @param {type} container
             * @returns {undefined}
             */
            function updateProduct(container) {
                var response = null;
                // First update product data
                // name, status, description, displayName
                productData = {
                    name: $('#productId', container).val(),
                    status: $('#productStatus', container).val(),
                    description: $('#productDescription', container).val(),
                    displayName: $('#productDisplayName', container).val(),
                    updatedByHsaid: 'hsaId'
                };
                $.ajax({
                    url: productPut,
                    type: 'PUT',
                    data: JSON.stringify(productData),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(productData) {
                        showGrowlMessage('Produkt uppdaterad.');
                        response = productData;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                        response = false;
                        if (textStatus==='error' && errorThrown==='Unauthorized') {
                            alert("Din användarsession har gått ut, du måste logga in på nytt!")
                            $(location).attr('href','../');
                        }
                    }
                });
                return response;
            }

            /**
             * Calls REST-API to save codes to product.
             * @param id
             * @param {type} container
             * @returns {undefined}
             */
            function setCodes(id, container) {
                var codes = $('#productCodeTable', container).dataTable().fnGetData();
                request = $.map(codes, function(e) {
                    return {
                        oid: e.oid,
                        code: e.code
                    };
                });
                request = addWaitingTimeCodes(request);
                $.ajax({
                    url: productPut + '/' + id + '/codes',
                    type: 'PUT',
                    data: JSON.stringify(request),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(codes) {
                        retCodes = codes;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                    }
                });
                return codes;
            }

            function getProductCodes(productId) {
                var retCodes = null;
                $.ajax({
                    url: productGet + '/' + productId + '/codes',
                    type: 'GET',
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',
                    async: false,
                    success: function(codes) {
                        retCodes = codes;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        showErrorGrowlMessage(jqXHR.responseText);
                    }
                });
                return retCodes;
            }

            /**
             * 
             * @param {type} request
             * @returns {unresolved}
             */
            function addWaitingTimeCodes(request) {
                var request = request.filter(function(element) {
                    return element.oid !== "oid.sll.vantetider";
                });
                var checked = false;
                if ($('#Mottagning').is(":checked")) {
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 1
                    });
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 2
                    });
                    checked = true;
                }
                if ($('#Operation').is(":checked")) {
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 5
                    });
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 6
                    });
                    checked = true;

                }
                if ($('#OperationMottagning').is(":checked")) {
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 3
                    });
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 4
                    });
                    checked = true;
                }
                if (checked) {
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 7
                    });
                    request.push({
                        oid: 'oid.sll.vantetider',
                        code: 8
                    });
                }
                return request;
            }

            function setWaitingTimeCheckbox(productCodes, container) {
                $.each(productCodes, function(key, val) {
                    if (val.oid === 'oid.sll.vantetider') {
                        if (val.code === "1" || val.code === "2") {
                            $("#Mottagning", container).prop("checked", true);
                        }
                        if (val.code === "3" || val.code === "4") {
                            $("#OperationMottagning", container).prop("checked", true);
                        }
                        if (val.code === "5" || val.code === "6") {
                            $("#Operation", container).prop("checked", true);
                        }
                    }
                });
            }

            /**
             * Add codes to table view
             * 
             * @param {type} table
             * @param {type} select
             * @param {type} oid
             * @returns {undefined}
             */
            function addCodeToTableView(table, select, oid) {
                var id = select.val();
                // Avoid duplicates
                var existing = $.grep(table.fnGetData(), function(e) {
                    return e.id === id && e.oid === oid;
                });
                if (existing.length === 0) {
                    var code = $.grep(viewData.codeSystem[oid].codes, function(e) {
                        return e.code === id;
                    });
                    console.log(code);
                    table.fnAddData({
                        codeSystem: viewData.codeSystem[oid].name,
                        code: id,
                        displayName: code[0].displayName,
                        oid: code[0].oid
                    });
                }
                // Reset selection
                select.chosen().val('');
                select.trigger('chosen:updated');
            }
        </script>
    </body>
</html>
